//
//  WBUserAccount.swift
//  daoge_sineweibo
//
//  Created by 伍禄林 on 16/10/11.
//  Copyright © 2016年 伍禄林. All rights reserved.
//

import UIKit

private let accountFile: NSString = "useraccount.json"
//用户账户信息
class WBUserAccount: NSObject {
    
    //访问令牌
    var access_token: String? //= "2.004FX32G07nppS377571b95d6RQ38D"
    //用户id
    var uid: String?
    //过期日期 单位秒
    var expires_in: TimeInterval = 0 {
        
        didSet{
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    var expiresDate: Date?
    
    var screen_name: String?
    
    var avatar_large: String?
    
    
    
    override init() {
        super.init()
        
        
        guard let filePath = accountFile.cz_appendDocumentDir(),
            let data = NSData(contentsOfFile: filePath),
        let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String:Any] else {
                return
        }
        
        yy_modelSet(with: dict ?? [:])
        
        if expiresDate?.compare(Date()) != .orderedDescending {
            
            print("token过期")
            
            access_token = nil
            uid = nil
            
            _ = try? FileManager.default.removeItem(atPath: filePath)
        }
        print("用户正常")
    }
    
    override var description: String {
        
        return yy_modelDescription()
    }
    
    func saveAccount()  {
        
        var dict = (self.yy_modelToJSONObject() as? [String: Any]) ?? [:]
        
        dict.removeValue(forKey: "expires_in")
        
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
            let filePath = accountFile.cz_appendDocumentDir() else {
             return
        }

        (data as NSData).write(toFile: filePath, atomically: true);
        
        print(filePath)
        
    }
    
}
